/*-------------------------------------------------------------------------

***************** Modification History ***********************************
   @doc
   @module msgfuncs.c - Functions for message retreival and display |
   @end

$Log: /SoftPay/SPK2SIM/Source/Msg/msgfuncs.c $
**************************************************************************

   Copyright (C) 1999 by VeriFone, Inc.

   All rights reserved.  No part of this software may be reproduced,
   transmitted, transcribed, stored in a retrieval system, or translated
   into any language or computer language, in any form or by any means,
   electronic, mechanical, magnetic, optical, chemical, manual or otherwise,
   without the prior written permission of VeriFone, Inc.

---------------------------------------------------------------------------*/
#define VSMSG_C

#include <stdio.h>
#include <stdlib.h>
#include <message.h>
#include <string.h>
#include <svctxo.h>
#include <aclstr.h>

#include <project.h>
/** /#define DEBUG_VSMSG*/
#ifdef DEBUG_VSMSG
#define DEBUG_95
#endif

#include <define.h>
#include <transact.h>
#include <msgfuncs.h>
#include <sizes.h>
#include <lct.h>
#include <tblutil.h>
#include <spdebug.h>
#include <pscalls.h>
#include <confio.h>
#include <table.h>
#include <ui.h>
#include <codesec.h>
#include <spamsg.h>

char szInvalidMessageFile[] = "-InvalidFile";
char szSuffixDAT[FILE_SUFFIX_SIZE + 1] = ".DAT";
char szSuffixFLD[FILE_SUFFIX_SIZE + 1] = ".FLD";

/*-------------------------------------------------------------------------
    Function :  inSelectMessageFile()
    Description :
    Parameters :
    Returns :
    Globals :
    Notes :
    Modification History :
      #     Date      Who                     Description
    ----- -------- ---------- ---------------------------------------------
      1    1/10/96  Eddy_B1    Creation.
      2    9/10/98 Page_K1    Change use of LCT.
--------------------------------------------------------------------------*/
int inSelectMessageFile(const char* szMessageFileSuffix) {
    static char szCurrentMessageFileName[FILENAME_SIZE + 1];
    char szNewMessageFileName[MESSAGE_SIZE + 1];

    memset(szNewMessageFileName, 0, MESSAGE_SIZE + 1);
    // We are changine englspa.dat so keep it in RAM, all others in Flash
    if (!strncmp(szMessageFileSuffix, "SPA", 3) || !strncmp(szMessageFileSuffix, "spa", 3))
        strcpy(szNewMessageFileName, szGetLanguageNamePrefix());
    else {
        strcpy(szNewMessageFileName, STATIC_DATA_PATH);    
        strcat(szNewMessageFileName, szGetLanguageNamePrefix());
    }

    strcat(szNewMessageFileName, szMessageFileSuffix);
    strcat(szNewMessageFileName, DAT_SUFFIX);

    if (strcmp(szCurrentMessageFileName, szNewMessageFileName)) {
        if (msg_select_file(szNewMessageFileName) < 0) {
            strcat(szNewMessageFileName, szInvalidMessageFile);
            vdDisplayErrorString(szNewMessageFileName);
            return (VS_ERR);
        }

        strcpy(szCurrentMessageFileName, szNewMessageFileName);
    }

    return (VS_SUCCESS);
}

/*-------------------------------------------------------------------------
    Function : vdDisplayErrorMessage()
    Description :
    Parameters :
    Returns :
    Globals :
    Notes :
    Modification History :
      #     Date      Who                     Description
    ----- -------- ---------- ---------------------------------------------
      1    1/11/96  Eddy_B1   Creation.
      1    1/23/96  Eddy_B1   Added the abs() call.
--------------------------------------------------------------------------*/
void vdDisplayErrorMessage(long lnMessageIndex) {
    vdDisplayMessageFromFile(lnMessageIndex, ERROR_MSG);
    vdSGErrorMessage(0L);
}

void vdDisplayMessage(const char* szMessage,int inMsgType) {
    if (szMessage != NULL)
        switch (inMsgType) {
        case ENTRY_MSG:
            vdDisplayString(szMessage);
            break;
        case STATUS_MSG:
            vdDisplayStatusString(szMessage);
            break;
        case ERROR_MSG:
            vdDisplayErrorString(szMessage);
            break;
        case WARNING_MSG:
            vdDisplayWarningString(szMessage);
            break;
        }
}

/*-------------------------------------------------------------------------
    Function : vdDisplayMessageFromFile()
    Description :
    Parameters :
    Returns :
    Globals :
    Notes :
    Modification History :
      #     Date      Who                     Description
    ----- -------- ---------- ---------------------------------------------
      1    1/11/96  Eddy_B1   Creation.
      1    1/23/96  Eddy_B1   Added the abs() call.
--------------------------------------------------------------------------*/
void vdDisplayMessageFromFile(long lnMessageIndex,int inMsgType) {
    char szMessage[MESSAGE_SIZE + 1];

    vdGetMessageFromFile(lnMessageIndex, szMessage);

    vdDisplayMessage(szMessage, inMsgType);
}




/*-------------------------------------------------------------------------
    Function :  vdGetMessageFromFile()
    Description :
    Parameters :
    Returns :
    Globals :
    Notes :
    Modification History :
      #     Date      Who                     Description
    ----- -------- ---------- ---------------------------------------------
      1    9/15/98 Page_K1    Call inGetDefaultLCT().
--------------------------------------------------------------------------*/
void vdGetMessageFromFile(long lnMessageIndex,char* szMessageBuffer) {
    int inMsgTblIndex;
    int inMessageIndex;
    char szFileNameBuffer[MSG_FILE_NAME_SIZE];

    inMsgTblIndex = (int) (lnMessageIndex >> 16);
    inMessageIndex = (int) (lnMessageIndex & 0x0000ffff);

    inGetDefaultLCT();
    memset(szFileNameBuffer, 0, MSG_FILE_NAME_SIZE);
    inGetMessageFileName(inMsgTblIndex, szFileNameBuffer);
    if (inMsgTblIndex > 0) {
        if (inSelectMessageFile(szFileNameBuffer) != VS_SUCCESS)
            return;
    }

    if (msg_get(abs(inMessageIndex), szMessageBuffer) == NULL)
        return;
}


/*-------------------------------------------------------------------------
    Function :  vdGetMessageFromThisFile()
    Description :
    Parameters :
    Returns :
    Globals :
    Notes :
    Modification History :
      #     Date      Who                     Description
    ----- -------- ---------- ---------------------------------------------
      1    9/15/98 Page_K1    Call inGetDefaultLCT().
--------------------------------------------------------------------------*/
void vdGetMessageFromThisFile(const  char* szFileNameSuffix,int inMessageIndex,char* szMessageBuffer) {
    inGetDefaultLCT();

    if (inSelectMessageFile(szFileNameSuffix) != VS_SUCCESS)
        return;

    if (msg_get(abs(inMessageIndex), szMessageBuffer) == NULL) {
        /** /pdebug(("%d msg indx not found.",inMessageIndex));*/
        return;
    }
}

/*-------------------------------------------------------------------------
    Function :  vdGetMessageFromReceiptFile()
    Description :
    Parameters :
    Returns :
    Globals :
    Notes :
    Modification History :
      #     Date      Who                     Description
    ----- -------- ---------- ---------------------------------------------
      1    9/15/98 Page_K1    Call inGetReceiptLCT().
--------------------------------------------------------------------------*/
void vdGetMessageFromReceiptFile(long lnMessageIndex,char* szMessageBuffer,TRANSACTION_OBJECT* pobTran) {
    int inMsgTblIndex;
    int inMessageIndex;
    char szFileNameBuffer[MSG_FILE_NAME_SIZE];

    inMsgTblIndex = (int) (lnMessageIndex >> 16);
    inMessageIndex = (int) (lnMessageIndex & 0x0000ffff);

    if ((getgrid() == 0) && (get_font_mode() == 2)) // 2 byte addressing scheme + 16x16 Font
        inLoadLCTRec(0);
    else
        inGetReceiptLCT(pobTran);

    memset(szFileNameBuffer, 0, MSG_FILE_NAME_SIZE);
    inGetMessageFileName(inMsgTblIndex, szFileNameBuffer);

    if (inMsgTblIndex > 0) {
        if (inSelectMessageFile(szFileNameBuffer) != VS_SUCCESS) {
            if ((getgrid() == 0) && (get_font_mode() == 2)) // 2 byte addressing scheme + 16x16 Font
                inGetDefaultLCT();  /// bring back the old LCT
            return;
        }
    }

    if (msg_get(abs(inMessageIndex), szMessageBuffer) == NULL) {
        if ((getgrid() == 0) && (get_font_mode() == 2)) // 2 byte addressing scheme + 16x16 Font
            inGetDefaultLCT();  /// bring back the old LCT
        return;
    }

    if ((getgrid() == 0) && (get_font_mode() == 2)) // 2 byte addressing scheme + 16x16 Font
        inGetDefaultLCT();  /// bring back the old LCT
}

/*-------------------------------------------------------------------------
    Function :      fUpdateSPAMessages()
    Description :   Extracts SoftPay Assist Messages from Config.Sys and creates
                    englspa.dat.
    Parameters :    None
    Returns :       TRUE or FALSE indicating success or failure
    Globals :       None
    Notes :         None
    Modification History :
      #     Date      Who                     Description
    ----- -------- ---------- ---------------------------------------------
      0   01/14/98 Kevin_V1   Creation.
--------------------------------------------------------------------------*/
VS_BOOL fUpdateSPAMessages(TRANSACTION_OBJECT* pobTran) {
    VS_BOOL fReturnValue = VS_TRUE;
    int inMsgNum,
    inLCTIdx,
    inResult,
    inLength,
    inHandle;
    char szConfigName[CONFIG_NM_SIZE + 1],
    szMessage[MESSAGE_SIZE + 1],
    szMessageCvt[MESSAGE_SIZE + 1],
    szMessageFileName[FILENAME_SIZE + 1];
    long lnResult;        

    /** /pdebug (("--fUpdateSPAMessages--"));*/

    /*
     *      Extract SPA messages from CONFIG.SYS
     *          Format MSGnn
     */
    for (inLCTIdx = 0; inLCTIdx < inGetLCTTotRecs(); inLCTIdx++) {
        inLoadLCTRec(inLCTIdx);
        for (inMsgNum = 1; ; ++inMsgNum) {
            sprintf(szConfigName, "G%02d%02d", inLCTIdx, inMsgNum);
            memset(szMessage, 0, sizeof(szMessage));
            if (get_env(szConfigName, szMessage, sizeof(szMessage)) <= 0) {
                /*
                         *      Read failed, if on first message then there were none, otherwise
                         *      close the file and exit loop.
                         */
                if (inMsgNum > 1) {
                    if ((inResult = close(inHandle)) < 0) {
                        extern int errno;
                        /** /pdebug (("(%d) Close Failed=%d/%d",inMsgNum,inResult,errno));*/
                        fReturnValue = VS_FALSE;
                    }
                }
                break;
            } else {
                /*
                         *      Removed CONFIG.SYS parameter
                         */
                put_env(szConfigName, "", 0);
                /*
                         *      Read success, if first message open "ENGLSPA.DAT" for over-writing.
                         *      Write Message to file in VLR format.
                         */
                if (inMsgNum == 1) {
                    strcpy(szMessageFileName, szGetLanguageNamePrefix());
                    strcat(szMessageFileName, "SPA");
                    strcat(szMessageFileName, DAT_SUFFIX);
                    if ((inHandle = open(szMessageFileName, O_TRUNC | O_CREAT | O_RDWR)) < 0) {
                        extern int errno;
                        /** /pdebug (("Open Failed=%s/%d/%d",szMessageFileName,inHandle,errno));*/
                        fReturnValue = VS_FALSE;
                        break;
                    }
                    /*
                                 *      TXO Message file requires 2 HEX Byte header with value 0x0200 at
                                 *      the beginning of the file.
                                 */ {
                        unsigned char ucHexHeader[2];

                        ucHexHeader[0] = 2;
                        ucHexHeader[1] = 0;
                        if ((inResult = write(inHandle, (char *) ucHexHeader, 2)) != 2) {
                            extern int errno;
                            /** /pdebug (("(%d) Hdr Write Failed=%d/%d",inMsgNum,inResult,errno));*/
                            close(inHandle);
                            fReturnValue = VS_FALSE;
                            break;
                        }
                    }
                }
                inLength = inConvertCase(szMessage, szMessageCvt);
                /** /pdebug (("(%d) Write %s=%d",inMsgNum,szMessage,inLength));*/
                if ((lnResult = write_vlr(inHandle, szMessageCvt, inLength)) != (long) inLength) {
                    extern int errno;
                    /** /pdebug (("(%d) Write Failed=%d/%d",inMsgNum,lnResult,errno));*/
                    close(inHandle);
                    fReturnValue = VS_FALSE;
                    break;
                }
            }
        }
    }

    return fReturnValue;
} /* End of fExtractSPAMessages() */

/*-------------------------------------------------------------------------
    Function :      inConvertCase()
    Description :   Converts SoftPay Assist Messages to upper and lower case.
                    '^' in the input string indicates switch to lower case, a
                    2nd '^' indicates switch back to upper case, etc.
    Parameters :    None
    Returns :       Length of new string.
    Globals :       None
    Notes :         Message In, and Message Out must be unique buffers;
    Modification History :
      #     Date      Who                     Description
    ----- -------- ---------- ---------------------------------------------
      0   01/14/98 Kevin_V1   Creation.
--------------------------------------------------------------------------*/
int inConvertCase(char* pszMsgIn,char* pszMsgOut) {
    int inPosOut,
    inPosIn;
    VS_BOOL fLower;

    /** /pdebug (("--inConvertCase--"));*/
    inPosIn = inPosOut = 0;
    fLower = VS_FALSE;
    while (pszMsgIn[inPosIn] != NULL_CH) {
        if (pszMsgIn[inPosIn] == '^') {
            fLower = !fLower;
            ++inPosIn;
            continue;
        }
        pszMsgOut[inPosOut++] = ((fLower && (pszMsgIn[inPosIn] > '@' && pszMsgIn[inPosIn] < '[')) ? pszMsgIn[inPosIn] + 32 : pszMsgIn[inPosIn]);
        ++inPosIn;
    }

    return inPosOut;
} /* End of inConvertCase() */

int MSGFUNCS_CODE_CHECK(char* a,char* b,short* c,char* d,unsigned char* e) {
    GET_VER(a, b, c, d, e);
    return 1;
}

/*-------------------------------------------------------------------------
    Function :      vdGetIdlePrompt()
    Description :   Gets a new idle prompt from the config.sys variable
                    IDLE then stores it in the SPA message file for idle
                    display's use.
    Parameters :    None
    Returns :       Nothing        
    Globals :       None
    Notes :         
    Modification History :
      #     Date      Who                     Description
    ----- -------- ---------- ---------------------------------------------
      0   07/11/00 Michele_M2   Creation.
--------------------------------------------------------------------------*/
void vdGetIdlePrompt(void) {
    int inHandle,
    inLength = 16;
    char szMessage[MESSAGE_SIZE + 1],
    szMessageCvt[MESSAGE_SIZE + 1],
    szMessageFileName[FILENAME_SIZE + 1];
    long lnRecNo;

    /* check to see if there is an Express Config variable for idle prompt */
    memset(szMessage, 0, sizeof(szMessage));
    if (get_env("IDLE", szMessage, sizeof(szMessage)) > 0) {
        strcpy(szMessageFileName, szGetLanguageNamePrefix());
        strcat(szMessageFileName, "SPA");
        strcat(szMessageFileName, DAT_SUFFIX);
        if ((inHandle = open(szMessageFileName, O_RDWR)) > 0) {
            memset(szMessageCvt, 0, sizeof(szMessageCvt));
            inConvertCase(szMessage, szMessageCvt);

            /* If they sent only one space then they want the default logo */
            if (strlen(szMessageCvt) == 1 && szMessageCvt[0] == ' ')
                inLength = 1;
            else
                pad(szMessageCvt, szMessageCvt, ' ', 16, CENTER);

            lnRecNo = (long) (IDLE_PROMPT_MSG & 0x0000ffff);
            if (seek_vlr(inHandle, ((long) abs((int) lnRecNo)), SEEK_SET) > 0L)
                write_vlr(inHandle, szMessageCvt, inLength);
            close(inHandle);
            /* Remove CONFIG.SYS parameter */
            put_env("IDLE", "", 0);
        } /* end if file opens OK */
    } /* end if config.sys Idle Prompt */

    return;
} /* end func vdGetIdlePrompt() */

#undef VSMSG_C

